#include "../Base/stdafx.h"
#include "EffectLib.h"
#include "../Base/DXDevice.h"

EffectLib* EffectLib::m_Singleton = NULL;

void DeleteEffect(pair<tstring, ID3D10Effect*> myPair) { myPair.second->Release(); }

EffectLib::EffectLib()
{

}

EffectLib::~EffectLib()
{
	Cleanup();
}

EffectLib* EffectLib::GetSingleton()
{
	if(m_Singleton == 0)
		m_Singleton = new EffectLib();
	return m_Singleton;
}

ID3D10Effect* EffectLib::CreateEffect(const tstring &file)
{
	DWORD ShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
	#if defined(_DEBUG) || defined(DEBUG)
		ShaderFlags |= D3D10_SHADER_DEBUG;
		ShaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
	#endif

	ID3D10Blob* ErrorsPtr = NULL;
	ID3D10Effect* Effect;

	if(m_Effects.find(file) != m_Effects.end())
		Effect = m_Effects.find(file)->second;
	else
	{
		HRESULT hres;
		hres = D3DX10CreateEffectFromFile(file.c_str(), NULL, NULL, "fx_4_0", 
			ShaderFlags, NULL, DXDEVICE->GetDevice(),  NULL, NULL, &Effect, &ErrorsPtr, NULL);
		if(ErrorsPtr)
		{
			char* errors = (char*)ErrorsPtr->GetBufferPointer();
			OutputDebugStringA(errors);
			if(hres != S_OK)
				return NULL;
		}
			m_Effects.insert(make_pair(file, Effect));
	}
	return Effect;
}

void EffectLib::Cleanup()
{
	for_each(m_Effects.begin(), m_Effects.end(), DeleteEffect);
}

void EffectLib::SetShadow(ID3D10ShaderResourceView *ShadowMap)
{
	m_ShadowMap = ShadowMap;
}

ID3D10ShaderResourceView* EffectLib::GetShadow() const
{
	return m_ShadowMap;
}